package com.shh.shojbackendquestionservice;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.init.InitExecutor;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.transport.config.TransportConfig;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.util.Collections;

@SpringBootApplication()
@MapperScan("com.shh.shojbackendquestionservice.mapper")
@EnableScheduling
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
@ComponentScan("com.shh")
@EnableDiscoveryClient
@EnableFeignClients(basePackages = {"com.shh.shojbackendserviceclient.service"})
public class ShojBackendQuestionServiceApplication {

    public static void main(String[] args) {

        SpringApplication.run(ShojBackendQuestionServiceApplication.class, args);
        init();
        initFlowRules();

    }

    /**
     * 初始化Sentinel 由于在yml中添加配置无效 所以才用手动
     */
    public static void init() {
        // 设置 Dashboard 地址
        System.setProperty(TransportConfig.CONSOLE_SERVER, "localhost:8080");
        //设置ip地址 为本机ip
        System.setProperty("csp.sentinel.heartbeat.client.ip", "192.168.1.5");
        // 初始化 Sentinel
        InitExecutor.doInit();
    }

    public static void initFlowRules() {
        FlowRule rule = new FlowRule();
        rule.setResource("api/question_submit/do"); // 资源名
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // QPS模式
        rule.setCount(0.2); // 阈值：0.2 QPS = 1次/5秒
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER); // 排队等待
        rule.setMaxQueueingTimeMs(5000); // 排队超时时间 = 5秒
        FlowRuleManager.loadRules(Collections.singletonList(rule));
    }


}
